

from flask import Flask, request, redirect, url_for, flash, render_template
from flask_sqlalchemy import SQLAlchemy
from flask import Blueprint
import os
from tools.Myfile import Myfile
from Models.School import School
from Models import db
from pymysql.connections import MysqlPacket
from werkzeug import datastructures

school_blue = Blueprint("School", __name__,url_prefix='/school')



@school_blue.route('/school',methods=["POST","GET"])
def hello_world():
    print(66666)
    return {'code': 0, 'msg': '查询成功'}
    # id = request.args.get('id')
    # school = db.session.query(School).filter(School.id == id).first()
    # return {'code':0,'msg':'查询成功','data':{'id':school.id,'name':school.name}}

@school_blue.route('/add',methods=["POST","GET"])
def hello_world_install():
    article1 = School(name='离线')
    article2 = School(name='在线')
    db.session.add(article1)
    db.session.add(article2)
    db.session.commit()  # 只要一访问浏览器，正确返回了hello world，说明事物提交成功
    return {'code':0,'msg':'创建成功'}

@school_blue.route('/update',methods=["POST","GET"])
def hello_world_update():
    # 改，先查询出来，再来修改
    result = School.query.filter(School.name == '在线').first()
    result.name = '6666'  # 将查询出来的所有的title =='aaa1'的记录，全部修改为'aaa111'
    db.session.commit()
    res = School.query.filter(School.name == '6666').first()

    return {'code':0,'msg':'修改成功','data':{'id':res.id,'name':res.name}}

@school_blue.route('/delete',methods=["POST","GET"])
def hello_world_delete():
    #操作步骤：先查后删除
    result = School.query.filter(School.name == '6666').first()
    db.session.delete(result)
    db.session.commit()
    return {'code':0,'msg':'删除成功'}

def upload(img,filename):
    img.save(os.path.join('./static/upload/'+'1',filename))
    # img.save(os.path.join(filename))

@school_blue.route('/add_goods',methods=['POST'])
def add_goods():
    # name = request.form.get('name')
    # price = request.form.get('price')
    img = request.files['img']
    print('这是img',img)
    myfile = Myfile()
    myfile.mkdir(1)
    # filename = myfile.rename(img.filename)
    filename = img.filename
    # sql = "insert into `goods` (`name`,`price`,`img`) values ('%s',%s,'%s')" % (name,price,filename)
    upload(img,filename)
    return {'code':200,'meg':'添加成功'}